﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Collections;

namespace Grishko.UIControls
{


    [System.Web.UI.ToolboxData("<{0}:Autocomplit runat=server></{0}:Autocomplit>"),
    DefaultProperty("Text")]
    public class Autocomplit :  WebControl,IPostBackDataHandler
    {

        static string ListControlID             = "WebMethodList";
        string TextValueKey                     = "TextValueKey";
        string IdValueKey                       = "IdValueKey";
        string NextCallCounterValueKey          = "NextCallCounterValueKey";
        string CssValueKey                      = "CssValueKey";
        string HightValueKey                    = "HightValueKey";
        string WebMethodKey                     = "WebMethodKey";
        string AutocomplitDivID                 = "AutocomplitDivID";
                
        public event EventHandler RowSelected;
        
        public static  ListBox  GetListBoxControl(List<ListItem> ListSource)
        {
                    ListBox lc = new ListBox() { Width = new Unit("99%"), Height = new Unit("100%") };
                    lc.ID = Grishko.UIControls.Autocomplit.ListControlID;
                    lc.CssClass  = "TextBox";
                    lc.Attributes.Add("onkeydown", "if(event.keyCode==13) OnSelectedRow();");
                    lc.Attributes.Add("onclick", "OnSelectedRow();");

                    if (null == ListSource)
                        return lc;

                    foreach (ListItem  i in ListSource)
                    {                        
                        lc.Items.Add(i) ;                        
                    }
                    return lc;

    }

        public virtual void onRowSelected(EventArgs arg)
        {            
            if (null != RowSelected)
                RowSelected(this, arg);
        }
        public string TextValue
        {

            get
            {

                object text = ViewState[TextValueKey];
                if (null == text)
                    return string.Empty;
                else
                    return (string)text;
            }
            set
            {

                ViewState[TextValueKey] = value;
            }
        }

        public string IdValue
        {

            get
            {

                object text = ViewState[IdValueKey];
                if (null == text)
                    return string.Empty;
                else
                    return (string)text;
            }
            set
            {

                ViewState[IdValueKey] = value;
            }
        }


        /// <summary>
        /// Web метод формата Func(text) 
        /// </summary>
        public string PageMethod
        {

            get
            {

                object text = ViewState[WebMethodKey];
                if (null == text)
                    return string.Empty;
                else
                    return (string)text;
            }
            set
            {

                ViewState[WebMethodKey] = value;
            }
        }

        
        public string CSS
        {

            get
            {

                object text = ViewState[CssValueKey];
                if (null == text)
                    return string.Empty;
                else
                    return (string)text;
            }
            set
            {

                ViewState[CssValueKey] = value;
            }
        }

        public string DivHight
        {

            get
            {

                object text = ViewState[HightValueKey];
                if (null == text)
                    return string.Empty;
                else
                    return (string)text;
            }
            set
            {

                ViewState[HightValueKey] = value;
            }
        }

        public int NextCallCounter
        {

            get
            {

                object text = ViewState[NextCallCounterValueKey];
                if (null == text)
                    return 3;
                else
                    return Convert.ToInt16 (text);
            }
            set
            {

                ViewState[NextCallCounterValueKey] = value;
            }
        }

        
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            string Script = "var NextCallCounter=0; var ListControlId=''; function CallPageMethod(e){ " + Environment.NewLine +

            "if(event.keyCode==13) {OnSelectedRow(); return;}" + Environment.NewLine +

            "if(e.keyCode==40) {var list= document.getElementById('WebMethodList'); if(null!=list) list.focus(); return;}" + Environment.NewLine +

            "if(NextCallCounter==" + NextCallCounter.ToString() + "){var txt= document.getElementById('"+this .UniqueID  +"').value; PageMethods." + PageMethod + "(txt,FillControlDiv); NextCallCounter=0;} else NextCallCounter=NextCallCounter+1;  }" + Environment.NewLine +

            "function FillControlDiv(ReturnHTML){var v = document.getElementById('" + DropDownControlID + "');v.innerHTML=ReturnHTML;};" + Environment.NewLine +

            "function OnSelectedRow(){var select =document.getElementById('WebMethodList');"+Environment .NewLine +

            " if(null==select) return; " + Environment.NewLine +

            " if(select.selectedIndex==-1) return; " + Environment.NewLine +

            "var t=select.options[select.selectedIndex].text;" + Environment.NewLine +

            
            "__doPostBack('"+ this.ClientID + "', select.value + '|'+t);   };";

            //Page.RegisterClientScriptBlock("Autocomplit_call_method", Script);
            ScriptManager.RegisterClientScriptBlock(this, typeof(Autocomplit), "Autocomplit_call_method", Script, true);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            Page.VerifyRenderingInServerForm(this);
            Page.ClientScript.GetPostBackEventReference(this, "");        
            
            Panel div = new Panel() { ID =AutocomplitDivID , Width = new Unit("100%") };
            
            if (!String.IsNullOrEmpty(DivHight))
                div.Height = new Unit(DivHight);

            TextBox t = new TextBox() { Width = new Unit("99%") };
            
            t.ID = this.UniqueID;
            
            t.Text = TextValue;
            
            t.Attributes.Add (  "onKeydown", "CallPageMethod(event);");
                                   
            t.CssClass = CSS;            
                        
            div.Controls.Add(t);

            Panel DropDownControl = new Panel() { Width = new Unit("100%"), ID = DropDownControlID };
            div.Controls .Add (DropDownControl );

            div.RenderControl(writer);
            

        }

        public string DropDownControlID { get { return "DropDownControl"; } }

        #region IPostBackDataHandler Members

        public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {

            if (postDataKey == this.UniqueID)
            {
                string s = postCollection["__EVENTARGUMENT"];
                if (s.Length == 0)
                    return false;

                string []arr= s.Split ("|".ToCharArray() [0]);
                if(arr .Length >0)
                    IdValue =arr[0];
                    TextValue =arr[1];                
                
                return true;
            }
            return false;
        }

        public void RaisePostDataChangedEvent()
        {
            onRowSelected(new EventArgs());
        }

        #endregion
    }
}

